package com.hu.util;

import com.aliyun.tea.*;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.UUID;

/**
 * 用来发送短信的工具类
 */
@Component
public class MessageUtil {

    private final com.aliyun.dysmsapi20170525.Client client;

    public MessageUtil() throws Exception {
        this.client = createClient(); // 构造时创建一次
    }

    private com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId("LTAI5tA1nNWQj92yV9xzPL8e")
                .setAccessKeySecret("cwxGMzgMkajlDNBVdyrotSjORpAG9i");
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public  String sendMessage(String phone) throws Exception {
        String code = String.format("%04d", new Random().nextInt(10000));

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest =
                new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                        .setSignName("阿里云短信测试")
                        .setTemplateCode("SMS_154950909")
                        .setPhoneNumbers(phone)
                        .setTemplateParam("{\"code\":\"" + code + "\"}")
                ;

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            if (error.getData() != null && error.getData().get("Recommend") != null) {
                System.out.println(error.getData().get("Recommend"));
            }
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return code;
    }
}

